$(function() {

	
  });
$("#add-a-credit-card").click(function(){
	$("#add-credit-card-box .credit-card-box").show({effect:"drop",direction:"up"},1000,function(){
		
	});
});

$(".dms .card-listing").on("click"," .credit-card .trash", function(){
	var cc = $(this).parents(".credit-card");
	var removeId = cc.find("input[name='cardId']").val();
	$.ajax({
		  type: "POST",
		  url: "/dms/creditCard/"+removeId+"/remove.json",
		  async:false
		}).done(function(data){
			if (typeof data!="undefined"&&data){
				cc.hide({effect:"drop",direction:"up"},1000,function(){
					cc.remove();
				});
			} 
		}).fail(function(data){
			console.log("fail,data="+data);
		}).always(function(data){
			console.log("always,data="+data);
		});
	
})

function hideBox(selector,effect){
	$(selector).hide({effect:effect,direction:"up"},1000,function(){
		
	});
}

function addCreditCardEntry(id){
	$(".dms .credit-card-entry-template .credit-card").clone().appendTo($(".dms .card-listing"));
	var newCard=$(".dms .card-listing span:last-child");
	newCard.find("input[name='cardId']").val(id);
	newCard.find(".card.type").html($("#credit-card-type").val());
	var cardNo=$("#credit-card-number").val();
	var cardNoDisp="xxxx-"+cardNo.substring(cardNo.length-4,cardNo.length);
	newCard.find(".card.number").html(cardNoDisp);
	newCard.find(".card.exp-date").html($("#expirationMonth").val()+"/"+$("#expirationYear").val());
	newCard.find(".card.name").html($("#credit-card-name").val());
	$(".credit-card-box").hide({effect:"drop",direction:"up"},1000,function(){
			$("#server-side-errMsg").html("");
			validator.resetForm();
			validator.currentForm.reset();
			newCard.show();
		});
}

	  $(".dms form .submit").click(function(){
		  $(this).parents("form").submit();
	  })
	  $(".dms .credit-card-box .cancel").click(function(){
		  $("#server-side-errMsg").html("");
		  validator.resetForm();
		  validator.currentForm.reset();
		  hideBox(".credit-card-box","drop");
	  })
	  $(".dms form .reset").click(function(){
		  $(this).parents("form")[0].reset();
	  })
	var validator = $(".dms form[name='dms-add-credit-card-form']").validate({
		errorContainer:	(".dms form[name='dms-add-credit-card-form'] div.errContainer" ),
		messages:{
			"payments.creditCard.creditCardType":"Missing credit card type.",
			"payments.creditCard.accountNumber":{
				required:"Missing credit card number.",
				creditcard:"credit card number is invalid."
			},
			"payments.creditCard.securityCode":"Missing security code.",
			expirationMonth:"Missing month of expiration date.",
			expirationYear:"Missing year of expiration date.",
			"payments.creditCard.nameAppearedOnCard":"Missing name on card.",
			"payments.creditCard.billingAddress.addressLine1":"Missing address.",
			"payments.creditCard.billingAddress.city":"Missing city.",
			"payments.creditCard.billingAddress.state":"Missing state.",
			"payments.creditCard.billingAddress.zip":{
				required:"Missing zip code.",
				minlength:"minimum 5 digits.",
				maxlength:"maximum 5 digits."
			}
		},
		submitHandler:function(){
//			console.log("form submitted!");
			$("#server-side-errMsg").html("");
			//$(".dms form[name='dms-add-credit-card-form']")[0].reset();
			$.ajax({
				  type: "POST",
				  url: "/dms/add-creditcard.json",
				  dataType: "json",
				  async:false,
				  data: {
					  type:$("#credit-card-type").val(),
					  accountNumber:$("#credit-card-number").val(),
					  securityCode:$("#credit-card-security-code").val(),
					  expirationDate:$("#expirationMonth").val()+"/01/"+$("#expirationYear").val(),
					  nameAppearedOnCard:$("#credit-card-name").val(),
					  "billingAddress.addressLine1":$("#addressLine1").val(),
					  "billingAddress.addressLine2":$("#addressLine2").val(),
					  "billingAddress.city":$("#city").val(),
					  "billingAddress.state":$("#state").val(),
					  "billingAddress.zip":$("#zip").val()
				  }
				}).done(function(data){
//					console.log("success,data="+data);
					if (typeof data.errMsgs!="undefined"&&data.errMsgs.length>0){
						for ( var int = 0; int < data.errMsgs.length; int++) {
							$("#server-side-errMsg").append("<li>"+data.errMsgs[int]+"</li>");
						}
					} else if (typeof data.creditCardId!="undefined"&&data.creditCardId!=""){
						addCreditCardEntry(data.creditCardId);
					}
				}).fail(function(data){
					console.log("fail,data="+data);
				}).always(function(data){
					console.log("always,data="+data);
				});
//			addCreditCardEntry();
			
			return false;
		}
	});
	  
	  //if no credit card is set, promopt "add a credit card
		$.validator.addMethod("addCreditCard", function(value, element) {
	        return $(element).parents("form").find("input[name='cardId']").length>0;
	    }, "Plaease add a credit card.");	  
		
		$.validator.addMethod("selectPayment", function(value, element) {
			//if no credit card is in list, don't fire this rule, fire this rule only there is at least one credit card in list but no credit card is selectd.
			return $(element).parents("form").find("input[name='cardId']").length==0||$(element).parents("form").find("input[name='cardId']:checked").length>0;
		}, "Plaease select a payment.");	  
	  
	  var selectPaymentFormValidator = $(".dms form[name='dms-select-payment-form']").validate({
		  rules:{
			  selectPayment:{
				  "addCreditCard":true,
				  "selectPayment":true
			  }
		  },
		  ignore:"",//validate hidden field "selectPayment"
		  errorContainer:	(".dms form[name='dms-select-payment-form'] div.errContainer" )
	  });
